//
//  GAOUserAccount.swift
//  Weibo28
//
//  Created by 高辰 on 16/5/12.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class GAOUserAccount: NSObject, NSCoding {
    //用户授权的唯一票据
    var access_token: String?
    //access_token的生命周期,单位是秒数
    var expires_in: NSTimeInterval = 0 {
        didSet {
            // 过期时间 = 当前时间+生命周期
            expiresDate = NSDate().dateByAddingTimeInterval(expires_in)
        }
    
    }
    //  过期时间
    var expiresDate: NSDate?
    
    //授权用户的UID
    var uid : Int64 = 0
    
    //用户名
    var name: String?
    
    //用户头像地址（大图）
    var avatar_large: String?
    //
    
    
    //kvc构造函数
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    //  MARK:归档,解档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeInt64(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeInt64ForKey("uid")
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
    //保存用户对象
    func saveUserAccount()-> Bool {
        //归档路径
        let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("useraccount.archiver")
        
      return NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    
    //读取保存的用户对象
   class func loadUserAccount()-> GAOUserAccount? {
        //解档路径
        let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("useraccount.archiver")
        
       return NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? GAOUserAccount
    
    }
    
    
    
}
